from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
# Create your models here.

class User(AbstractUser):
    username = models.CharField(unique=True,max_length=100)
    email = models.EmailField(unique=True)
    full_name = models.CharField(unique=True,max_length=100)
    otp = models.CharField(max_length=100,null=True,blank=True)
    refresh_token = models.CharField(max_length=100,null=True,blank=True)
    #用户模型唯一的标识字段
    USERNAME_FIELD = 'email'
    #创建用户时必需的字段，除USERNAME_FIELD和password之外
    REQUIRED_FIELDS = ['username']

    def __str__(self):
        return self.email
    
    def save(self,*args,**kwargs):
        email_username,full_name = self.email.split("@")
        if self.full_name == "" or self.full_name==None:
            self.full_name = email_username
        if self.username == "" or self.username == None:
            self.username = email_username
        super(User,self).save(*args,**kwargs)



#用户配置信息
class Profile(models.Model):
    #一旦删除User，则连带删除
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    image = models.FileField(upload_to="user_folder",default="default.jpg",null=True,blank=True)
    full_name = models.CharField(max_length=100)
    country = models.CharField(max_length=100,null=True,blank=True)
    about = models.TextField(null=True,blank=True)
    date = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        if self.full_name:
            return str(self.full_name)
        else:
            return str(self.user.full_name)
        

    def save(self,*args,**kwargs):
        if self.full_name == "" or self.full_name==None:
            self.full_name = self.user.username
        super(Profile,self).save(*args,**kwargs)


#信号处理函数
def create_user_profile(sender,instance,created,**kwargs):
    if created:
        Profile.objects.create(user=instance)

def save_user_profile(sender,instance,**kwargs):
    instance.profile.save()

#将函数连接到post_save信号上，只监听 User模型的保存事件
post_save.connect(create_user_profile,sender=User)
post_save.connect(save_user_profile,sender=User)